﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using EPiServer.Core;
using NUnit.Framework;
using OpenWaves.EPiServer.CustomProperties;

namespace OpenWaves.EPiServer.UnitTests
{
    [TestFixture]
    public class PropertySerializationExceptionTests
    {
        [Test]
        public void TestRestoringValuesAfterSerializationCycle()
        {
            var exception = new PropertySerializationException("FooMessage", "BarProperty", new PageReference(13), "FooValue");
            var deserialized = CycleSerialization(exception);

            StringAssert.Contains("FooMessage", deserialized.Message);
            Assert.That(deserialized.PropertyName, Is.EqualTo("BarProperty"));
            Assert.That(deserialized.PageLink, Is.EqualTo(new PageReference(13)));
            Assert.That(deserialized.PropertyValue, Is.EqualTo("FooValue"));

        }

        private static T CycleSerialization<T>(T graph)
        {
            MemoryStream ms = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, graph);

            ms.Seek(0, SeekOrigin.Begin);

            return (T)formatter.Deserialize(ms);
        }
    }
}